#include "thread_pool.h"
#include <mysql/mysql.h>
#include <stdio.h>
#include <sys/syslog.h>

extern MYSQL* conn;

void delDir(MYSQL* conn, int fid);

void rmdirCommand(task_t * task)
{
    //获得filename
    char filename[128] = {0};
    strcpy(filename, task->data);
    printf("filename: %s\n", filename);

    //获得userid
    int userid = -1;
    getUserid(task->peerfd, &userid);
    printf("userid: %d\n", userid);

    //查询当前的pwdid
    int pwdid = -1;
    char query[512] = {0};
    sprintf(query,
            "SELECT pwdid FROM t_user WHERE userid=%d",
            userid);
    mysql_query(conn, query);
    MYSQL_RES* res = mysql_store_result(conn);
    MYSQL_ROW row = mysql_fetch_row(res);
    pwdid = atoi(row[0]);
    mysql_free_result(res);
    printf("pwdid: %d\n", pwdid);

    //查询这个filename对应的fid
    int fid = -1;
    memset(query, 0, sizeof(query));
    sprintf(query,
            "SELECT fid FROM t_file WHERE owner_id=%d AND parent_id=%d AND filename='%s' AND type='d'",
            userid, pwdid, filename);
    mysql_query(conn, query);
    res = mysql_store_result(conn);
    int count = mysql_num_rows(res);
    if(count == 0){     //目录不存在
        fprintf(stderr, "Directory id not exists.\n");
        sendMsg(task->peerfd, MSG_TYPE_NOT_EXIST, "Directory is not exists.");;
        return;
    } else {    //目录存在
        row = mysql_fetch_row(res);
        pwdid = atoi(row[0]);
        mysql_free_result(res);
        fid = atoi(row[0]);
        printf("fid: %d\n", fid);
    }

    //递归删除该文件夹以及该文件夹下的所有文件和目录
    delDir(conn, fid);
    printf("Rmdir successful.\n");
    sendMsg(task->peerfd, MSG_TYPE_SUCCESS, "Rmdir successfully.");
    syslog(LOG_INFO, "User %d rmdir %d successfully.", userid, fid);
    
}

//递归删除目录
void delDir(MYSQL* conn, int fid){
    char query[128] = {0};
    sprintf(query,
            "SELECT fid,type FROM t_file WHERE parent_id=%d",
            fid);
    mysql_query(conn, query);
    MYSQL_RES* res = mysql_store_result(conn);
    MYSQL_ROW row;
    int child_fid = -1;
    char type[2] = {0};
    while((row = mysql_fetch_row(res)) != NULL){
        child_fid = atoi(row[0]);
        strcpy(type, row[1]);
        if(!strcmp(type, "d")){
            delDir(conn, child_fid);
        } else {
            char query1[128] = {0};
            sprintf(query1,
                    "DELETE FROM t_file WHERE fid=%d",
                    child_fid);
            mysql_query(conn, query1);
        }
    }
    char query2[128] = {0};
    sprintf(query2,
            "DELETE FROM t_file WHERE fid=%d",
            fid);
    mysql_query(conn, query2);

    mysql_free_result(res);
}


//2期
int deleteDir(const char* path){
    //打开目录流
    DIR* pdir = opendir(path);
    if(!pdir){
        perror("open dir failed");
        return 1;
    }
    //普通文件删除，目录文件递归
    struct dirent* curr;
    errno = 0;
    while((curr = readdir(pdir)) != NULL){
        char* filename = curr->d_name;
        char substr[256];
        sprintf(substr,"%s/%s", path,filename);
        if(strcmp(filename,".") ==0 || strcmp(filename,"..") == 0){
            continue;
        }
        if(curr->d_type == DT_DIR){
            deleteDir(substr);
        }else {
            unlink(substr);
        }
    }
    if(errno){
        return 1;
    }
    rmdir(path);
    //关闭目录流
    closedir(pdir);
    return 0;
}

//2期功能
void rmdirCommand1(task_t * task)
{
    train_t t;
    memset(&t, 0, sizeof(t));
    int ret = deleteDir(task->data);
    if(ret != 0){
        strcpy(t.buff, "rmdir failed");
        t.len = strlen(t.buff);
        sendn(task->peerfd, &t, 4 + t.len);
        syslog(LOG_WARNING, "User execute RMDIR command: FAILED.");
        return;
    }
    strcpy(t.buff, "rmdir succeed");
    t.len = strlen(t.buff);
    sendn(task->peerfd, &t, 4 + t.len);
    syslog(LOG_INFO, "User execute RMDIR command: SUCCESSFUL.");
}
